package com.whitehot.ndkmaster;

/**
 * Created by yutf on 2017/9/30 0030.
 */

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加解密的java实现
 */
public class AESUtils
{

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String keys, String data)
    {
        SecretKeySpec key = new SecretKeySpec(keys.getBytes(), ALGORITHM);
        Cipher cipher = null; // 创建密码器
        try
        {
            cipher = Cipher.getInstance(ALGORITHM_STR);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] fl = cipher.doFinal(data.getBytes());
            return new String(Base64.encode(fl, Base64.DEFAULT));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param base64Data
     * @return
     * @throws Exception
     */
    public String decryptData(String keys, String base64Data)
    {
        SecretKeySpec key = new SecretKeySpec(keys.getBytes(), ALGORITHM);
        Cipher cipher = null;
        try
        {
            cipher = Cipher.getInstance(ALGORITHM_STR);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64.decode(base64Data, Base64.DEFAULT)));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * hex字符串 转 byte数组
     *
     * @param s
     * @return
     */
    private static byte[] hex2byte(String s)
    {
        if (s.length() % 2 == 0)
        {
            return hex2byte(s.getBytes(), 0, s.length() >> 1);
        } else
        {
            return hex2byte("0" + s);
        }
    }

    private static byte[] hex2byte(byte[] b, int offset, int len)
    {
        byte[] d = new byte[len];
        for (int i = 0; i < len * 2; i++)
        {
            int shift = i % 2 == 1 ? 0 : 4;
            d[i >> 1] |= Character.digit((char) b[offset + i], 16) << shift;
        }
        return d;
    }
}